//
//  VideoManager.swift
//  AudioToolProject
//
//  Created by 邹琳 on 2019/5/8.
//  Copyright © 2019 邹琳. All rights reserved.
//

import UIKit
import AVFoundation
class VideoManager: NSObject {
	
    static func get_video_face(_ url:URL,finish:(UIImage,Int)->Void){
        let asset = AVURLAsset(url: url)
        let gen = AVAssetImageGenerator(asset: asset)
        let duration = Int(asset.duration.value) / Int(asset.duration.timescale)
        gen.appliesPreferredTrackTransform = true
        let time = CMTimeMakeWithSeconds(0.5, preferredTimescale: 600)
        do{
            let image = try gen.copyCGImage(at: time, actualTime: nil)
            let thumbImage = UIImage(cgImage: image)
            finish(thumbImage,duration)
        }catch{
            print(error)
        }
    }
    
    static func get_video_audio(_ url:URL,finish:@escaping(Data?,Int)->Void){
        let exportURL = URL(fileURLWithPath: get_audio_name(".m4a"))
        try? FileManager.default.removeItem(at: exportURL)
        let videoAsset = AVURLAsset(url: url)
        /** 获取时长 */
        let audioTimeRange = CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration)
        let audioTime = Int(videoAsset.duration.value) / Int(videoAsset.duration.timescale)
        
        guard let audioTrack = videoAsset.tracks(withMediaType: .audio).last else{
            finish(nil,0)
            return
        }
        
        let composition = AVMutableComposition()
        let compositionTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
        try? compositionTrack?.insertTimeRange(audioTimeRange, of: audioTrack, at: CMTime.zero)
        
        let exportSession = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetAppleM4A)
        exportSession?.outputURL = exportURL
        exportSession?.outputFileType = AVFileType.m4a
        exportSession?.timeRange = audioTimeRange
        exportSession?.exportAsynchronously(completionHandler: {
            if exportSession?.status == AVAssetExportSession.Status.completed{
                do{
                    let data = try Data(contentsOf: exportURL)
                    finish(data,audioTime)
                }catch{
                    print(error)
                    finish(nil,0)
                }
            }else{
                finish(nil,0)
                print("error = \(exportSession?.error?.localizedDescription ?? "失败")")
            }
        })
    }
}
